package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;


@RestController
@RequestMapping("user")
public class UserController {
    @Reference
    private UserService userService;


    @RequestMapping("getUsername")
    public Result getUsername(Principal principal){
        try {
            String name = principal.getName();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,name);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
    @RequestMapping("getMenu")
    public Result getMenu(Principal principal){
        try {
            String username = principal.getName();
            List<Menu> list =  userService.getMenu(username);

            return new Result(true,MessageConstant.GET_MENU_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MENU_FAIL);
        }
    }

    /**
     * 根据账户修改密码
     * @param principal
     * @param pass
     * @return
     */
    @RequestMapping("chengedByUsername")
    public Result chengedByUsername(Principal principal,@RequestParam("password") String pass){
        try {
            String username = principal.getName();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String password = encoder.encode(pass);
            userService.chengedByUsername(username,password);
            return new Result(true,"修改密码成功,请记好新密码:"+pass);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改密码失败");
        }
    }
}
